package com.xinchao.controller;

import com.xinchao.cache.RedisCacheDao;
import com.xinchao.constant.BusinessConstant;
import com.xinchao.constant.CacheConstant;
import com.xinchao.constant.JSONConstant;
import com.xinchao.constant.ResponseConstant;
import com.xinchao.model.User;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.service.UserService;
import com.xinchao.util.UUIDUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理登录Controller
 *
 * @author dxy
 * @date 2018/7/4 19:24
 */
@Controller
@RequestMapping(value = "/api/web")
public class WebController {
	@Autowired
	private UserService userService;
	@Autowired
	private RedisCacheDao redisCacheDao;

	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping("/login")
	public Object login(String userName, String password) {
		User user = userService.getUserByUserName(userName);
		if (user == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
		}
		if (BusinessConstant.STATUS_DISABLE == user.getStatus()) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户已被禁用，请联系管理员");
		}
		//验证密码
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
		}
		String oldPassword = user.getPassword();
		String md5Password = DigestUtils.md5Hex(password);
		if (!md5Password.equals(oldPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码错误");
		}
		//验证通过，生成一个token，将token放入redis中
		String token = UUIDUtils.getUUIDString();
		redisCacheDao.putCache(CacheConstant.CACHE_NAME_TOKEN, userName, token);
		//将userName，token返回
		Map<String, String> returnMap = new HashMap<>();
		returnMap.put(JSONConstant.JOSN_KEY_USER_NAME, userName);
		returnMap.put(JSONConstant.JOSN_KEY_TOKEN, token);
		return returnMap;
	}

}
